package br.com.channelll.client;

import br.com.channelll.client.validator.ValidateEmail;
import br.com.channelll.client.validator.ValidateLogin;
import br.com.channelll.client.validator.ValidateSenha;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.KeyListener;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign;
import com.extjs.gxt.ui.client.widget.layout.ColumnData;
import com.extjs.gxt.ui.client.widget.layout.ColumnLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.tips.ToolTipConfig;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Channelll extends LayoutContainer implements EntryPoint {

	private VerticalPanel vp;
	private final TextField<String> txtLogin = new TextField<String>();
	private final TextField<String> txtEmail = new TextField<String>();
	private final TextField<String> txtSenha = new TextField<String>();
	private final Button btnOk = new Button("OK");

	@Override
	public void onModuleLoad() {
		vp = new VerticalPanel();
		vp.setSpacing(5);
		createColumnForm();
		RootPanel.get("bloco").add(vp);
	}

	private void createColumnForm() {

		FormData formData = new FormData("100%");
		FormPanel panel = new FormPanel();
		panel.setFrame(true);
		panel
				.setHeading("<center>Entre já na rede de notícias social</center>");
		panel.setSize(600, -1);
		panel.setLabelAlign(LabelAlign.LEFT);
		panel.setButtonAlign(HorizontalAlignment.CENTER);

		LayoutContainer main = new LayoutContainer();
		main.setLayout(new ColumnLayout());

		LayoutContainer left = new LayoutContainer();
		left.setStyleAttribute("paddingRight", "20px");
		FormLayout layout = new FormLayout();
		layout.setLabelAlign(LabelAlign.LEFT);
		left.setLayout(layout);

		txtLogin.setFieldLabel("Login");
		left.add(txtLogin, formData);

		txtEmail.setFieldLabel("Email");
		left.add(txtEmail, formData);

		txtSenha.setFieldLabel("Senha");
		left.add(txtSenha, formData);

		btnOk.setEnabled(false);
		// left.add(btnOk,formData);
		btnOk.addListener(Events.OnClick,new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				IncluiLogin.execute(txtLogin.getValue());
			}
		});
		
		txtLogin.addListener(Events.OnBlur, new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				boolean ok = ValidateLogin.execute(txtLogin.getValue().trim());
				if (ok) {
					txtLogin.clearInvalid();
					Info.display(txtLogin.getValue(), "Usuario válido");
				} else {
					txtLogin.forceInvalid("Usuario Inválido");
					Info.display(txtEmail.getValue(),
							"Usuário Inválido: preencha com 3 a 20 caracteres");
				}
			};
		});

		txtLogin.addKeyListener(new KeyListener() {
			@Override
			public void componentKeyUp(ComponentEvent event) {
				// TODO Auto-generated method stub
				if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
					validateAndSubmit();
				} else {
					validateData();
				}
			}

			@Override
			public void componentKeyDown(ComponentEvent event) {
				if (txtLogin.getValue().length() >= 20) {
					if ((event.getKeyCode() != KeyCodes.KEY_BACKSPACE)
							&& (event.getKeyCode() != KeyCodes.KEY_DELETE)
							&& (event.getKeyCode() != KeyCodes.KEY_TAB))
						event.stopEvent();
				}
			}
		});

		txtEmail.addListener(Events.OnBlur, new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				boolean ok = ValidateEmail.execute(txtEmail.getValue().trim());
				if (ok) {
					txtEmail.clearInvalid();
					Info.display(txtEmail.getValue(), "Email vaaaaaálido");
				} else {
					txtEmail.forceInvalid("Email Inválido");
					Info.display(txtEmail.getValue(),
							"Email Inválido: siga o modelo email@domain.com");
				}
			};
		});
		txtEmail.addKeyListener(new KeyListener() {
			@Override
			public void componentKeyUp(ComponentEvent event) {
				// TODO Auto-generated method stub
				if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
					validateAndSubmit();
				} else {
					validateData();
				}
			}
		});

		txtSenha.setPassword(true);
		txtSenha.addListener(Events.OnBlur, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				boolean ok = ValidateSenha.execute(txtSenha.getValue().trim());
				if (ok) {
					txtSenha.clearInvalid();
					Info.display(txtSenha.getValue(), "OKKK");
				} else {
					txtSenha.forceInvalid("Senha Inválida");
					Info.display(txtSenha.getValue(),
							"Senha Inválida: preencha com 4 a 10 caracteres");
				}
			};
		});
		txtSenha.addKeyListener(new KeyListener() {
			@Override
			public void componentKeyUp(ComponentEvent event) {
				// TODO Auto-generated method stub
				if (event.getKeyCode() == KeyCodes.KEY_ENTER) {
					validateAndSubmit();
				} else {
					validateData();
				}
			}

			public void componentKeyDown(ComponentEvent event) {
				if (txtSenha.getValue().length() >= 10) {
					if ((event.getKeyCode() != KeyCodes.KEY_BACKSPACE)
							&& (event.getKeyCode() != KeyCodes.KEY_DELETE)
							&& (event.getKeyCode() != KeyCodes.KEY_TAB))
						event.stopEvent();
				}
			}
		});

		LayoutContainer right = new LayoutContainer();
		right.setStyleAttribute("paddingLeft", "3px");
		layout = new FormLayout();
		layout.setLabelAlign(LabelAlign.LEFT);
		right.setLayout(layout);

		final Button btnValida = new Button();
		btnValida.setIconStyle("/resources/images/default/view_refresh.jpg");
		btnValida.setToolTip(new ToolTipConfig("Veri fica se usuário existe"));
		btnValida.addListener(Events.OnClick, new Listener<BaseEvent>() {
			@Override
			public void handleEvent(BaseEvent be) {
				ValidaLogin.execute(txtLogin.getValue());
			}
		});

		right.add(btnValida, formData);

		main.add(left, new ColumnData(.5));
		main.add(right, new ColumnData(.001));

		panel.add(main, new FormData("100%"));

		panel.addButton(btnOk);
		vp.add(panel);
	}

	private boolean validateData() {
		btnOk.setEnabled(false);
		if ((txtLogin.getValue() == null) || (txtEmail.getValue() == null)
				|| (txtSenha.getValue() == null)) {
			return false;
		}
		boolean ok = ValidateEmail.execute(txtEmail.getValue().trim())
				&& ValidateSenha.execute(txtSenha.getValue().trim())
				&& ValidateLogin.execute(txtLogin.getValue().trim());
		if (ok) {
			btnOk.setEnabled(true);
		}
		return ok;
	}

	private void validateAndSubmit() {
		if (validateData()) {
			Info.display("Adicionar", "Adicionar Usuário");
		}
	}

}
